package com.sdry.untils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class FileUtil {
	/**
     * user: Rex
     * date: 2016年12月29日  上午12:25:04
     * @param dir
     * void
     * TODO 判断路径是否存在，如果不存在则创建
     */
    public static void mkdirs(String dir){
        if(StringUtils.isEmpty(dir)){
            return;
        }
        
        File file = new File(dir);
        if(file.isDirectory()){
            return;
        } else {
            file.mkdirs();
        }
    }

    private static final String ENCODING = "UTF-8";
    private static final String CONTENT_DISPOSITION = "Content-Disposition";
    private static final String ATTACHMENT = "attachment;filename=";
    private static final String CONTENT_TYPE = "application/octet-stream;charset=UTF-8";
    private static final String CACHE_CONTROL = "Cache-Control";
    private static final String NO_CACHE = "no-cache";
    private static final String PRAGMA = "Pragma";
    private static final String EXPIRES = "Expires";
    private static final String APPLICATION_X_MSDOWNLOAD = "application/x-msdownload";

    public static void download2(String path, HttpServletResponse response) {
        OutputStream fos = null;
        FileInputStream fis = null;
        try {
            response.setHeader(PRAGMA, NO_CACHE);
            response.setHeader(CACHE_CONTROL, NO_CACHE);
            response.setCharacterEncoding(ENCODING);
            response.setHeader(CONTENT_DISPOSITION, ATTACHMENT + URLEncoder.encode(path, ENCODING));
            response.setContentType(CONTENT_TYPE);
            response.setDateHeader(EXPIRES, 0);
            fos = response.getOutputStream();
            File file = new File(path);
            if (file.exists()) {
                fis = new FileInputStream(file);
                FileCopyUtils.copy(fis, fos);
            }
            fis.close();
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(fis!=null){
                    fis.close();
                }
                if (fos!=null){
                    fos.close();
                }
            }catch (Exception e){
                e.getMessage();
            }

        }
    }

    /**
     * 文件上传方法
     * @param file  图片名称
     * @param type  上传类型（0:图片，1:文件）
     * @return  返回成功，失败
     */
    public static Map upload(MultipartFile file, Integer type) {
        String prefix;
        String dateStr;
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            if(file!=null){
                String originalName = file.getOriginalFilename();
                assert originalName != null;
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                Date date = new Date();
                String uuid = UUID.randomUUID()+"";
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dateStr = simpleDateFormat.format(date);
                String filepath;
                if(type == 0){
                    filepath = "D:\\attachment\\workPlan\\" + dateStr+"\\"+uuid+"." + prefix;
                }else{
                    filepath = "D:\\attachment\\workPlan\\" + dateStr+"\\"+originalName;
                }

                File files=new File(filepath);
                //打印查看上传路径
                System.out.println(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
                String data;
                if(type == 0){
                    data = "/attachment/workPlan/"+ dateStr+"/"+uuid+"." + prefix;
                }else{
                    data = "D:/attachment/workPlan/"+ dateStr+"/"+ originalName;
                }
                Map<String,Object> map=new HashMap<>(16);
                map.put("code",0);
                map.put("msg","");
                map.put("data", data);
                return map;
            }
        }catch (Exception ignored){
        }finally{
            try {
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException ignored) {
            }
        }
        Map<String,Object> map= new HashMap<>(16);
        map.put("code",1);
        map.put("msg","");
        return map;
    }
}
